<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/11/29 19:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Index extends API_Controller
{

    // 模块
    private $module = '';

    // Model 类
    private $model = null;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->_collectParams()->_instantModel();
    }

    /**
     * 收集参数
     */
    private function _collectParams()
    {
        $this->gets = !empty($this->input->get()) ? $this->input->get() : array();
        $this->posts = !empty($this->input->post()) ? $this->input->post() : array();
        $this->params = $this->gets + $this->posts;
        unset($this->params['token']);
        return $this;
    }

    /**
     * 模块化
     */
    private function _instantModel()
    {
        if (empty($this->params['module'])) {
            $this->output->send(array(
                'state' => false,
                'error' => '参数错误'
            ));
        }

        try {
            $version = $this->uri->segment(1);
            $interface = $this->uri->segment(2);
            $this->module = strtolower($this->params['module']);
            $this->model = 'api/' . $version . '/' . $interface . '/' . ucfirst($this->module) . '_Model';
            $this->load->model($this->model, $this->module);
        } catch(Exception $e) {
            $this->output->send(array(
                'state' => false,
                'error' => '接口或版本错误'
            ));
        }
    }

    /**
     * 主函数
     */
    public function execute()
    {
        try {
            $this->{$this->module}->run($this->params);
        } catch (PDOException $e) {
            $this->output->send(array(
                'state' => false,
                'error' => '接口不存在'
            ));
        }
    }

}
